package org.extreme.web.core.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.extreme.web.core.action.ActionException;
import org.extreme.web.core.action.IAction;
import org.extreme.web.core.cfg.WebCfg;
import org.extreme.web.core.cfg.WebGlobal;
import org.extreme.web.core.env.Env;
import org.extreme.web.core.resolver.IResolver;
import org.extreme.web.core.route.IRoutes;
import org.extreme.web.core.view.IRender;

public class MainServlet extends HttpServlet {
	
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected transient ServletContext context;
	
    protected IRoutes routes;
    protected IResolver resolver;
    protected IRender render;
    
	@Override
	public void service(HttpServletRequest req, HttpServletResponse resp)
	        throws ServletException, IOException {
		
        Env.create(req, resp, context);//创建环境
        try{
	        IAction action = resolver.resolvePath();//解析action
	        if(action==null){
	        	render.render404();
	        }else{
	        	action.getInvoker().invoke();//执行action
	        }
        }catch(Exception e){
            throw new ServletException(e);
        }finally{
        	Env.destroy();
        }
	}
	


    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init();
        WebCfg cfg = loadConfig(config);
        routes = WebGlobal.getRoutes(); 
        resolver = WebGlobal.getResolver();
        resolver.setRoutes(routes);
        render =  WebGlobal.getDefaultRender();
        context = config.getServletContext();
    }
    
    private WebCfg loadConfig(ServletConfig config){
    	String configClassName = config.getInitParameter("pconfig");
		WebCfg cfg = null;
		try {
			cfg = (WebCfg) Class.forName(configClassName).newInstance();
			cfg.init();
		} catch (InstantiationException e) {
			e.printStackTrace();
			throw new ActionException("config instance error.");
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new ActionException("creating config error : IllegalAccessException.");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new ActionException("could not find PConfig class");
		}
		return cfg;
	}
    
    @Override
    public void destroy(){
    }
}
